using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace SqlTools.SchemaReader
{
	public class Column : ColumnBase
	{
		private bool _isPrimaryKey = false;
		private bool _isForeignKey = false;
		private bool _isIdentity = false;

		private Check _check;
		private Default _default;

		public Column() : this("", 0) { }

		public Column(string name, int id)
			: base (name, id)
		{
			_check = null;
			_default = null;
		}

		public bool IsPrimaryKey
		{
			get { return _isPrimaryKey; }
			internal set { _isPrimaryKey = value; }
		}

		public bool IsForeignKey
		{
			get { return _isForeignKey; }
			internal set { _isForeignKey = value; }
		}

		public bool IsIdentity
		{
			get { return _isIdentity; }
			internal set { _isIdentity = value; }
		}

		public Check Check
		{
			get { return _check; }
			internal set { _check = value; }
		}

		public Default Default
		{
			get { return _default; }
			internal set { _default = value; }
		}

		public override DbObjectType Type
		{
			get { return DbObjectType.Column; }
		}

		public override XmlElement CreateXmlElement(XmlDocument doc, XmlNode parent)
		{
			XmlElement el = base.CreateXmlElement(doc, parent);

			el.Attributes.Append(doc.CreateAttribute("isprimarykey")).Value = _isPrimaryKey.ToString();
			el.Attributes.Append(doc.CreateAttribute("isforeignkey")).Value = _isForeignKey.ToString();
			el.Attributes.Append(doc.CreateAttribute("isidentity")).Value = _isIdentity.ToString();

			if ( _check != null )
				_check.SaveXml(doc, el);

			if ( _default != null )
				_default.SaveXml(doc, el);

			return el;
		}

		public override void LoadXml(XmlElement el, Database db)
		{
			base.LoadXml(el, db);

			string bvalue = "";

			bvalue = el.GetAttribute("isprimarykey");
			if ( !bool.TryParse(bvalue, out _isPrimaryKey) )
				_isPrimaryKey = false;

			bvalue = el.GetAttribute("isforeignkey");
			if ( !bool.TryParse(bvalue, out _isForeignKey) )
				_isForeignKey = false;

			bvalue = el.GetAttribute("isidentity");
			if ( !bool.TryParse(bvalue, out _isIdentity) )
				_isIdentity = false;

			XmlNodeList nodes = el.GetElementsByTagName("Check");
			if ( nodes.Count > 0 )
			{
				_check = new Check("", 0, _id);
				_check.LoadXml(nodes[0] as XmlElement, db);
			}

			nodes = el.GetElementsByTagName("Default");
			if ( nodes.Count > 0 )
			{
				_default = new Default("", 0, _id);
				_default.LoadXml(nodes[0] as XmlElement, db);
			}
		}
	}
}
